package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class ApiUserController {

    @Autowired
    private UserService userService;

    // 获取所有用户列表的API
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    // 更新用户状态的API
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/update-status")
    public Map<String, Object> updateStatus(@RequestParam("userId") Long userId, @RequestParam("status") Integer status) {
        userService.updateStatus(userId, status);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户状态已更新");
        return response;
    }

    // 删除用户的API
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/delete")
    public Map<String, Object> deleteUser(@RequestParam("userId") Long userId) {
        userService.delete(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户已删除");
        return response;
    }

    // 获取当前登录用户的API
    @GetMapping("/current")
    public User getCurrentUser(@RequestParam("username") String username) {
        return userService.findByUsername(username);
    }
}